import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import {
  getMenuList,
  addMenu,
  updateMenu,
  delMenuById
} from "@/api/system/menu";
import { assertResponse } from "@/api/utils";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

export function useMenu() {
  const form = reactive({
    title: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "目录" : "primary";
      case 1:
        return text ? "菜单" : "primary";
      case 2:
        return text ? "按钮" : "info";
      case 3:
        return text ? "外链" : "danger";
      case 4:
        return text ? "iframe" : "warning";
    }
  };

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{row.title}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "type",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getMenuType(row.type)} effect="plain">
          {getMenuType(row.type, true)}
        </el-tag>
      )
    },
    {
      label: "路由名称",
      prop: "name"
    },
    {
      label: "路由路径",
      prop: "component",
      formatter: ({ path, component }) =>
        isAllEmpty(component) ? path : component
    },
    {
      label: "权限标识",
      prop: "btnPerm"
    },
    {
      label: "排序",
      prop: "rank",
      width: 100
    },
    {
      label: "隐藏",
      prop: "showLink",
      formatter: ({ showLink }) => (showLink ? "否" : "是"),
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    await getMenuList()
      .then(res => assertResponse(res, "加载菜单失败"))
      .then(data => {
        let newData = data;
        if (!isAllEmpty(form.title)) {
          // 前端搜索菜单名称
          newData = newData.filter(item => item.title.includes(form.title));
        }
        dataList.value = handleTree(newData); // 处理成树结构
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function formatHigherMenuOptions(treeList) {
    if (!treeList || !treeList.length) return [];
    // 使用映射方法来创建新的树节点列表，过滤掉不满足条件的节点
    const newTreeList = treeList
      .filter(node => node.type <= 1) // 筛选出type小于等于1的节点
      .map(node => {
        // 对筛选出的每个节点进行处理
        node.children = formatHigherMenuOptions(node.children); // 递归处理子节点
        return node;
      });
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          type: row?.type ?? 0,
          higherMenuOptions: formatHigherMenuOptions(cloneDeep(dataList.value)),
          parentId: row?.parentId ?? 0,
          title: row?.title ?? undefined,
          name: row?.name ?? undefined,
          path: row?.path ?? undefined,
          component: row?.component ?? undefined,
          icon: row?.icon ?? undefined,
          rank: row?.rank ?? 99,
          btnPerm: row?.btnPerm ?? undefined,
          method: row?.method ?? undefined,
          keepAlive: row?.keepAlive ?? 0,
          showLink: row?.showLink ?? 1,
          frameSrc: row?.frameSrc ?? undefined
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了菜单名称为「${curData.name}」的这条数据`, {
            type: "success"
          });
        }
        FormRef.validate(valid => {
          if (valid) {
            if (curData.parentId === 0 && curData.type != 0) {
              message("只有新增目录时上级菜单可不选!", {
                type: "warning"
              });
              return;
            }
            // 表单规则校验通过
            const request =
              title === "新增"
                ? addMenu(curData)
                : updateMenu(curData.id, curData);
            request
              .then(res => assertResponse(res, `${title}失败`))
              .then(() => {
                chores();
                onSearch();
              })
              .finally(() => {
                done(); // 无论成功失败都关闭弹框
              });
          }
        });
      }
    });
  }

  function extractIds(menuItems: Array<any>, ids: number[] = []): number[] {
    // 遍历当前层级的菜单项
    for (const item of menuItems) {
      // 添加当前项的id到结果数组
      ids.push(item.id);

      // 如果当前项有子菜单，则递归调用此函数处理子菜单
      if (item.children && item.children.length > 0) {
        ids = extractIds(item.children, ids);
      }
    }

    return ids;
  }
  function handleDelete(row) {
    let ids: number[] = [];
    if (row.children) {
      const idList: number[] = extractIds(row.children);
      idList.push(row.id);
      ids = idList;
    } else {
      ids.push(row.id);
    }
    delMenuById(ids)
      .then(res => assertResponse(res, `$删除${row.title}失败`))
      .then(() => {
        message(`您删除了名称为${row.title}的这条数据`, {
          type: "success"
        });
        onSearch();
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange
  };
}
